<?php

abstract class Controller {

    /**
     * @var User
     */
    protected $user;

    /**
     * @var Exception
     */
    protected $error;

    public function __construct() {
        if (isset($_SESSION['user'])) {
            $this->user = $this->model('User');
            $this->user->load($_SESSION['user']);
        }
    }

    /**
     *  Undefined route fallback
     */
    public function __call($name, $args) {
        if (in_array($name, ['GET_' . DEFAULT_ACTION, 'POST_' . DEFAULT_ACTION])) {
            if (isset($this->user)) {
                $this->view('home/menu');
            } else {
                $this->view('home/index');
            }
        }
    }

    public function route(callable $action/* , $verb , $args */) {
        if (isset($this->user)) {
            // $args = $args ? array_values($args) : [];
            call_user_func_array($action, $this->get_postback());
        } else {
            $this->error = new Exception(Strings::MESSAGE_0046);
            $this->view('home/index');
        }
    }

    protected function get_postback() {
        $form = [];
        foreach ($_POST as $key => $value) {
            $form[$key] = filter_var($value, FILTER_SANITIZE_STRING);
        }
        return $form ? array_values($form) : [];
    }

    protected function model($model) {
        require_once 'app/models/' . $model . '.php';
        return new $model();
    }

    protected function view($view, $model = NULL) {
//        set_exception_handler(function(Exception $e) {
//            print get_class($e) . " thrown within the exception handler. Message: " . $e->getMessage() . " on line " . $e->getLine();
//        });
        $twig = new Template($this->error);
        require_once 'app/views/' . $view . '.php';
    }

}
